<template>
  <div class="manager-list-tab-panel">
    <el-form ref="form" :model="form" label-width="0px">
      <div>
        <tx-button-add :name="$dictValue('新增{name}')" @click="handleNew()" />
        <div style="float: right">
          <tx-button-add
            :icon="allowSort ? '' : 'el-icon-tickets'"
            :name="allowSort ? '保存排序' : '修改排序'"
            @click="updateSort"
          /><tx-button-add
            v-if="allowSort"
            icon=""
            name="取消排序"
            class="dialog-cancel-btn"
            style="background: #1d3f6a"
            @click="cancelSort"
          />
        </div>
      </div>
      <tx-list-table
        :table="table"
        ref="listTable"
        row-key="index"
        v-loading="table.loading"
      >
        <tx-table-column-text label="排序" width="60">
          <template slot-scope="scope">{{
            scope.scope.scope.$index + 1
          }}</template>
        </tx-table-column-text>
        <!-- 专家字段 -->
        <column
          :rules="formRules"
          :content="content"
          :label="$dictValue('{name}姓名')"
          field="name"
          showKey="expertName"
        />
        <tx-table-column-text
          :label="$dictValue('{name}类型')"
          v-if="show('expertSourceType')"
        >
          <template slot-scope="scope">
            <tx-table-select
              :entity="scope.row"
              name="sourceType"
              :rules="formRules.sourceType"
              :prop="buildRowProp(scope, 'sourceType')"
              :action="scope.row.$action"
              :placeholder="$dictValue('请输入{name}类型')"
              :options="{ values: pageData.expertSourceType }"
            />
          </template>
        </tx-table-column-text>
        <column
          :rules="formRules"
          :content="content"
          label="联系电话"
          field="phone"
          showKey="expertPhone"
        />
        <column
          :rules="formRules"
          :content="content"
          label="所在单位"
          field="superiorOrgName"
          showKey="expertOrgName"
        />
        <column
          :rules="formRules"
          :content="content"
          label="单位地址"
          field="officeAddress"
          showKey="expertOrgAddress"
        />
        <tx-table-column-text
          :label="$dictValue('{name}级别')"
          v-if="show('expertUserLevel')"
        >
          <template slot-scope="scope">
            <tx-table-select
              :entity="scope.row"
              name="userLevel"
              :rules="formRules.userLevel"
              :prop="buildRowProp(scope, 'userLevel')"
              :action="scope.row.$action"
              :placeholder="$dictValue('请输入{name}级别')"
              :options="{
                values: pageData.expertUserLevel,
              }"
            />
          </template>
        </tx-table-column-text>
        <tx-table-column-text label="职称级别" v-if="show('expertJobLevel')">
          <template slot-scope="scope">
            <tx-table-select
              :entity="scope.row"
              name="jobLevel"
              :rules="formRules.jobLevel"
              :prop="buildRowProp(scope, 'jobLevel')"
              :action="scope.row.$action"
              placeholder="请输入职称级别"
              :options="{
                values: pageData.expertJobLevel,
              }"
            />
          </template>
        </tx-table-column-text>
        <column
          :rules="formRules"
          :content="content"
          label="职务"
          field="job"
          showKey="expertJob"
        />
        <column
          :rules="formRules"
          :content="content"
          label="特长描述"
          field="desc"
          showKey="expertDesc"
        />

        <!-- 救援队伍 -->
        <column
          :rules="formRules"
          :content="content"
          :label="$dictValue('{name}名称')"
          field="orgName"
          showKey="jydwOrgName"
        />

        <column-jydw-source-type
          :rules="formRules"
          :content="content"
          :label="$dictValue('{name}类型')"
          field="sourceType"
          showKey="jydwSourceType"
        />

        <!-- <tx-table-column-text
          :label="$dictValue('{name}类型')"
          v-if="show('jydwSourceType')"
        >
          <template slot-scope="scope">
            <tx-table-select
              :entity="scope.row"
              name="sourceType"
              :rules="formRules.sourceType"
              :prop="buildRowProp(scope, 'sourceType')"
              :action="scope.row.$action"
              :placeholder="$dictValue('请输入{name}类型')"
              :options="{ values: pageData.jydwSourceType }"
            />
            <tx-table-select
              :entity="scope.row"
              name="sourceType"
              :rules="formRules.sourceType"
              :prop="buildRowProp(scope, 'sourceType')"
              :action="scope.row.$action"
              :placeholder="$dictValue('请输入{name}类型')"
              :options="{ values: pageData.jydwSourceType }"
            />
          </template>
        </tx-table-column-text> -->
        <column-jydw-source-level
          :rules="formRules"
          :content="content"
          :label="$dictValue('{name}级别')"
          field="sourceLevel"
          showKey="jydwSourceLevel"
        />

        <column
          :rules="formRules"
          :content="content"
          label="管理员姓名"
          field="name"
          showKey="jydwName"
        />
        <column
          :rules="formRules"
          :content="content"
          label="管理员职务"
          field="job"
          showKey="jydwJob"
        />
        <column
          :rules="formRules"
          :content="content"
          label="手机号"
          field="phone"
          showKey="jydwPhone"
        />

        <!--  -->
        <column
          :rules="formRules"
          :content="content"
          :label="$dictValue('{name}名称')"
          field="orgName"
        />

        <!--  -->
        <tx-table-column-text
          :label="$dictValue('{name}类型')"
          v-if="show('resourceType')"
        >
          <template slot-scope="scope">
            <tx-table-select
              :entity="scope.row"
              name="resourceType"
              :rules="formRules.resourceType"
              :prop="buildRowProp(scope, 'resourceType')"
              :action="scope.row.$action"
              :placeholder="$dictValue('请输入{name}类型')"
              :options="{ values: pageData.resourceType }"
            />
          </template>
        </tx-table-column-text>

        <tx-table-column-text
          :label="$dictValue('{name}类型')"
          v-if="show('fhmbSourceType')"
        >
          <template slot-scope="scope">
            <tx-table-select
              :entity="scope.row"
              name="sourceType"
              :rules="formRules.sourceType"
              :prop="buildRowProp(scope, 'sourceType')"
              :action="scope.row.$action"
              :placeholder="$dictValue('请输入{name}类型')"
              :options="{ values: pageData.fhmbSourceType }"
            />
          </template>
        </tx-table-column-text>

        <column
          :rules="formRules"
          :content="content"
          label="管理员姓名"
          field="name"
        />
        <column
          :rules="formRules"
          :content="content"
          label="管理员职务"
          field="job"
        />
        <column
          :rules="formRules"
          :content="content"
          label="手机号"
          field="phone"
        />

        <tx-table-column-action width="230" align="left" :key="$columnKey()">
          <template slot-scope="scope">
            <el-form
              :ref="`form${scope.scope.scope.$index}`"
              :model="form.record"
              :rules="formRules"
              style="display: none"
            >
              <tx-form-input
                :entity="form.record"
                :name="item"
                v-for="(item, i) in content.field"
                :key="i"
              />
            </el-form>
            <el-button
              type="primary"
              size="mini"
              v-if="scope.row.$action != 'modify'"
              class="table-edit-btn"
              @click="handleEdit(scope)"
              >编辑
            </el-button>
            <el-button
              type="primary"
              size="mini"
              v-if="scope.row.$action == 'modify'"
              @click="handleSave(scope)"
              class="table-save-btn"
              >保存
            </el-button>
            <el-button
              size="mini"
              type="warning"
              v-if="scope.row.$action == 'modify'"
              @click="handleCancel(scope)"
              class="table-cancel-btn"
              >取消
            </el-button>
            <tx-button-text-delete
              class="table-del-btn"
              v-if="
                scope.row.$action == 'modify' &&
                content.deleteController == 'OrgController'
              "
              :controller="content.deleteController"
              :success="$handleQuery"
              target="记录"
              :body="{ id: scope.row.id, orgId: scope.row.orgId }"
            />

            <tx-button-text-delete
              class="table-del-btn"
              v-if="
                scope.row.$action == 'modify' &&
                ['UserController', 'AdminController'].includes(
                  content.deleteController
                )
              "
              :controller="content.deleteController"
              :success="$handleQuery"
              target="记录"
              idKey="id"
              :idValue="scope.row.id"
            />
          </template>
        </tx-table-column-action>
      </tx-list-table>
      <!-- {{
        $nextTick(() => {
          $initDragTable($refs["listTable"], table.page, "records");
        })
      }} -->
    </el-form>
  </div>
</template>
<script>
import pageData from "./default.json";

import Column from "../column/column.vue";
import ColumnJydwSourceLevel from "../column/column-jydw-source-level.vue";
import ColumnJydwSourceType from "../column/column-jydw-source-type.vue";

export default {
  props: {
    active: {
      type: [String],
      default: "",
    },
    name: {
      type: [String],
      default: "",
    },
    dict: {
      type: Object,
      default() {
        return {};
      },
    },
    content: {
      type: Object,
      default() {
        return {
          controller: null,
          props: {},
          columns: [],
        };
      },
    },
  },
  data() {
    return {
      allowSort: false,
      pageData,
      table: {
        loading: false,
        query: {},
        sort: {
          descs: ["updateTime"],
        },
        page: this.$yzvue.initPage(),
      },

      // dict: dicts[this.name],
      initData: {
        $checkAll: false,
        $checked: [],
        $isIndeterminate: false,
        $sourceLevel: undefined,
        $visible: false,
        areaCode: "150000000000",
        areaName: "内蒙古自治区",
        city: "",
        cityOrgId: "",
        cityOrgName: "",
        country: "86",
        county: "",
        countyOrgId: "",
        countyOrgName: "",
      },
      form: {
        record: {
          name: "",
          resourceType: "",
          sourceType: [],
          sourceLevel: {},
          orgName: "",
          job: "",
          phone: "",
          superiorOrgName: "",
          officeAddress: "",
          jobLevel: "",
          desc: "",
        },

        records: [],
      },
      formRules: {
        name: this.$rule.name("姓名", null, 32),
        resourceType: this.$rule.requireds("类型不允许为空"),
        sourceType: this.$rule.requireds("类型不允许为空"),
        sourceLevel: this.$rule.requireds("级别不允许为空"),
        jobLevel: this.$rule.requireds("级别不允许为空"),
        orgName: this.$rule.name("单位", null, 32),
        job: this.$rule.name("职务", null, 32),
        phone: this.$rule.mobile("手机号", true),
        officeAddress: this.$rule.name("单位地址", null, 200),
        superiorOrgName: this.$rule.name("所在单位", null, 32),
        desc: this.$rule.name("特长描述", null, 200),
      },
    };
  },

  components: {
    Column,
    ColumnJydwSourceLevel,
    ColumnJydwSourceType,
  },
  watch: {
    active: {
      handler(n, o) {
        if (n && n == this.name) {
          this.loadTable();
        }
      },
    },
  },
  mounted() {
    if (this.active == this.name) {
      this.loadTable();
    }
  },

  methods: {
    show(column) {
      return this.$in(column, this.content.columns);
    },
    handlePageChange(size, current) {
      this.loadTable(null, size, current);
    },

    handleNew() {
      // Object.keys(this.form.record).forEach((v) => {
      //   this.form.record[v] = "";
      // });
      let newRow = Object.assign({ $action: "modify" }, this.form.record );
      this.table.page.records.push({...newRow, ...this.initData});
      console.log(this.table);
    },

    handleQuery() {
      this.loadTable();
    },

    controller(name) {
      if (name == "list") return this.$api[this.content.listController];
      if (name == "update") return this.$api[this.content.updateController];
      if (name == "new") return this.$api[this.content.newController];
      if (name == "delete") return this.$api[this.content.deleteController];
    },

    loadTable() {
      let param = this.$handleQueryParam();
      (param.body.isLeader = this.content.dict.isLeader),
        (this.table.loading = true);
      this.controller("list").list(param, (res) => {
        this.table.loading = false;
        console.log(res);
        for (let ri = 0; ri < res.data.length; ri++) {
          const re = res.data[ri];
          re.$action = "view";
          re.$visible = false;
          re.$checked = [];
          re.$checkAll = false;
          re.$isIndeterminate = false;
        }
        this.$yzvue.assembleBody(this.table.page, { records: res.data });
        this.form.records = res.data;
        // this.$nextTick(() => {
        //   this.$initDragTable(
        //     this.$refs["listTable"],
        //     this.table.page,
        //     "records"
        //   );
        // });
      });
    },

    buildRowProp($scope, field) {
      let {
        scope: { scope },
      } = $scope;
      return `records.${scope.$index}.${field}`;
    },

    // 编辑
    handleEdit($scope) {
      $scope.row.$action = "modify";
      $scope.row.$origin = this.$lodash.pick($scope.row, this.content.fields);
    },

    // 保存
    handleSave($scope) {
      Object.assign(this.form.record, $scope.row);
      this.$handleFormValidate(`form${$scope.scope.scope.$index}`, () => {
        let pack = {
          body: this.$lodash.pick($scope.row, ["id", ...this.content.fields]),
        };

        let isModify = pack.body.id;
        // if (!isModify) {
        Object.assign(pack.body, {
          menuID: this.getParameter("menuId"),
          areaCode: this.$userInfo.areaCode,
          createdBy: this.$userInfo.phone,
          pageType: this.$userInfo.pageType,
        });
        // }
        this.table.loading = true;
        let newMethod = this.controller("new").new;
        let updateMethod = this.controller("update").update;
        this.$invokeSave(pack, "id", newMethod, updateMethod, (res) => {
          this.table.loading = false;
          if (res && res.data) {
            $scope.row.$action = "view";
            if (!isModify) {
              $scope.row.id = res.data;
            }
          }
        });
      });
    },
    // 取消
    handleCancel($scope) {
      Object.assign($scope.row, $scope.row.$origin);
      $scope.row.$action = "view";
      this.$refs["form"].clearValidate();
    },
    //删除
    handleDelete($scope) {
      let {
        scope: { scope },
      } = $scope;
      this.table.page.records.splice(scope.$index, 1);
      // 请求后台接口删除数据库数据
    },
    updateSort() {
      if (this.allowSort == false) {
        this.$initDragTable(
          this.$refs["listTable"],
          this.table.page,
          "records"
        );
        this.beforeSortData = JSON.parse(
          JSON.stringify(this.table.page.records)
        );
      } else {
        let sortController = this.content.sortController;
        let params = this.table.page.records
          ?.filter((i) => (sortController == "OrgController" ? i.orgId : i.id))
          ?.map((i, k) => {
            return {
              id: sortController == "OrgController" ? i.orgId : i.id,
              udOrder: k + 1,
            };
          });
        this.$api[this.content.sortController].sort({ body: params }, (res) => {
          if (res.code == 0) {
            this.loadTable();
            this.$stopDragTable();
          }
        });
      }
      this.allowSort = !this.allowSort;
    },
    cancelSort() {
      this.allowSort = !this.allowSort;
      // this.this.table.page.records = JSON.parse(JSON.stringify(this.beforeSortData))
      // this.$initDragTable(this.$refs["listTable1"],
      //       this.table.page,
      //       "records1")
      this.$stopDragTable();
      this.loadTable();
    },
  },
};
</script>

<style lang="scss">
$car-table-border-color: #e4e4e4;
$car-table-title-color: #f5f5f5;

.manager-list-tab-panel {
  .tx-list-query {
    margin: 0px;

    // border: 2px solid $c-bd-menu;
  }
  .tx-block {
    width: auto;
    margin: 15px 0px;
    background-color: $c-bg-query;
    border: 1px solid $c-bd-content;
  }

  .el-table td.el-table__cell {
    padding: 8px 0px 0px 0px;
    .cell > span {
      display: block;
      padding-bottom: 13px;
      line-height: 30px;
    }
    .tx-table-column-action {
      display: block;
      padding-bottom: 10px;
    }

    .el-input__inner {
      height: 30px;
      line-height: 30px;
      padding: 0px 5px;
    }
    .el-form-item {
      margin-bottom: 13px;
    }
    .el-form-item__content {
      line-height: 30px;
    }
    .el-form-item__error {
      padding-top: 0px;
    }
  }
}
</style>
